<script lang="ts" setup>
import { computed, reactive, ref, unref } from 'vue'

import { Checkbox, Col, Form, Input, Row } from 'ant-design-vue'
import LoginFormTitle from './LoginFormTitle.vue'

import { LoginStateEnum, useFormRules, useFormValid, useLoginState } from './useLogin'
import { useMessage } from '@/hooks/web/useMessage'

import { useUserStore } from '@/store/modules/employee'
import { usePermissionStore } from '@/store/modules/permission'

import { useGlobSetting } from '@/hooks/setting'
import { useDesign } from '@/hooks/web/useDesign'

import { HashingFactory } from '@/utils/cipher'

const FormItem = Form.Item
const InputPassword = Input.Password

const { notification } = useMessage()
const { prefixCls } = useDesign('login')
const userStore = useUserStore()
const permissionStore = usePermissionStore()

const { captchaEnable } = useGlobSetting()

const { setLoginState, getLoginState } = useLoginState()
const { getFormRules } = useFormRules()

const formRef = ref()
const loading = ref(false)
const rememberMe = ref(false)

const verify = ref()

const formData = reactive({
  userName: 'sxc001',
  pwd: '123456',
  captchaVerification: '',
})

const { validForm } = useFormValid(formRef)

const getShow = computed(() => unref(getLoginState) === LoginStateEnum.LOGIN)

// 获取验证码
async function getCode() {
  // 情况一，未开启：则直接登录
  if (captchaEnable === 'false') {
    await handleLogin({})
  }
  else {
    // 情况二，已开启：则展示验证码；只有完成验证码的情况，才进行登录
    // 弹出验证码
    verify.value.show()
  }
}

async function handleLogin(params) {
  const data = await validForm()
  if (!data)
    return
  try {
    loading.value = true
    const userInfo = await userStore.login({
      pwd: HashingFactory.MD5().hash(data.pwd).toUpperCase(),
      userName: data.userName,
      captchaVerification: params.captchaVerification,
      mode: 'none', // 不要默认的错误提示
    })
    if (userInfo) {
      permissionStore.changePermissionCode(userInfo.componentCodes)
      notification.success({
        message: '登录成功',
        description: `欢迎回来: ${userInfo.realName}`,
        duration: 3,
      })
    }
  }
  finally {
    loading.value = false
  }
}
</script>

<template>
  <LoginFormTitle v-show="getShow" class="enter-x" />
  <Form
    v-show="getShow" ref="formRef" class="enter-x p-4" :model="formData" :rules="getFormRules"
    @keypress.enter="handleLogin"
  >
    <FormItem name="userName" class="enter-x">
      <Input
        v-model:value="formData.userName" size="large" placeholder="账号"
        class="fix-auto-fill"
      />
    </FormItem>
    <FormItem name="pwd" class="enter-x">
      <InputPassword
        v-model:value="formData.pwd"
        size="large"
        visibility-toggle
        placeholder="密码"
        class="fix-auto-fill"
      />
    </FormItem>

    <Row class="enter-x">
      <Col :span="12">
        <FormItem>
          <!-- No logic, you need to deal with it yourself -->
          <Checkbox v-model:checked="rememberMe" size="small">
            记住我
          </Checkbox>
        </FormItem>
      </Col>
      <Col :span="12">
        <FormItem :style="{ 'text-align': 'right' }">
          <!-- No logic, you need to deal with it yourself -->
          <a-button type="link" size="small" @click="setLoginState(LoginStateEnum.RESET_PASSWORD)">
            忘记密码?
          </a-button>
        </FormItem>
      </Col>
    </Row>

    <FormItem class="enter-x">
      <a-button type="primary" size="large" block :loading="loading" @click="getCode">
        登录
      </a-button>
    </FormItem>
  </Form>
</template>
